<template>
  <div class="app-container" v-loading="loading">
    <a-tabs v-model:value="activeTab">
      <a-tab-pane key="approval" tab="任务办理" v-if="processed">
        <a-card class="box-card" v-if="taskFormOpen">
          <template #title>填写表单</template>
          <div class="cu-content">
            <v-form-render :form-json="{}" :form-data="{}" ref="vfRenderRef" />
          </div>
        </a-card>

        <a-card class="box-card">
          <template #title>审批流程</template>
          <a-row>
            <a-col :span="20" :offset="2">
              <a-form ref="taskFormRef" :model="taskForm" :rules="rules" :label-col="{ span: 6 }">
                <a-form-item label="审批意见" name="comment">
                  <a-textarea v-model:value="taskForm.comment" :rows="5" placeholder="请输入审批意见" />
                </a-form-item>
                <a-form-item label="抄送人" name="copyUserIds">
                  <template v-for="(item, index) in copyUser" :key="index">
                    <a-tag closable @close="handleClose('copy', item)">
                      {{ item.nickName }}
                    </a-tag>
                  </template>
                  <a-button type="primary" shape="circle" @click="onSelectCopyUsers">
                    <template #icon><PlusOutlined /></template>
                  </a-button>
                </a-form-item>
                <a-form-item label="指定审批人" name="nextUserIds">
                  <template v-for="(item, index) in nextUser" :key="index">
                    <a-tag closable @close="handleClose('next', item)">
                      {{ item.nickName }}
                    </a-tag>
                  </template>
                  <a-button type="primary" shape="circle" @click="onSelectNextUsers">
                    <template #icon><PlusOutlined /></template>
                  </a-button>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>

          <a-row type="flex" justify="center" :gutter="10">
            <a-col :span="1.5" v-if="buttonPermissions.complete">
              <a-button type="primary" @click="handleComplete">
                <template #icon><CheckCircleOutlined /></template>
                通过
              </a-button>
            </a-col>
            <a-col :span="1.5" v-if="buttonPermissions.delegate">
              <a-button type="primary" @click="handleDelegate">
                <template #icon><SwapOutlined /></template>
                委派
              </a-button>
            </a-col>
            <a-col :span="1.5" v-if="buttonPermissions.addSign">
              <a-button type="primary" @click="handleAddSign">
                <template #icon><PlusCircleOutlined /></template>
                加签
              </a-button>
            </a-col>
            <a-col :span="1.5" v-if="buttonPermissions.transfer">
              <a-button type="primary" @click="handleTransfer">
                <template #icon><SyncOutlined /></template>
                转办
              </a-button>
            </a-col>
            <a-col :span="1.5" v-if="buttonPermissions.return">
              <a-button type="primary" @click="handleReturn">
                <template #icon><UndoOutlined /></template>
                退回
              </a-button>
            </a-col>
            <a-col :span="1.5" v-if="buttonPermissions.reject">
              <a-button type="primary" @click="handleReject">
                <template #icon><CloseCircleOutlined /></template>
                拒绝
              </a-button>
            </a-col>
          </a-row>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="form" tab="表单信息">
        <div v-if="formVisible">
         
          <component :is="componentPath" :formData="formData"></component>
        </div>
      </a-tab-pane>

      <a-tab-pane key="record" tab="流转记录">
        <a-card>
          <a-timeline>
            <a-timeline-item v-for="(item, index) in historyProcNodeList" :key="index" :color="tagType(item.endTime)">
              <a-card>
                <template #title>
                  <div style="font-weight: 700">{{ item.activityName }}</div>
                </template>
                <div v-if="item.activityType === 'startEvent'">{{ item.assigneeName }} 在 {{ item.createTime }} 发起流程</div>
                <div v-if="item.activityType === 'userTask'">
                  <a-descriptions bordered :column="5" :labelStyle="{ 'font-weight': 'bold' }">
                    <a-descriptions-item label="实际办理">{{ item.assigneeName || '-' }}</a-descriptions-item>
                    <a-descriptions-item label="候选办理">{{ item.candidate || '-' }}</a-descriptions-item>
                    <a-descriptions-item label="接收时间">{{ item.createTime || '-' }}</a-descriptions-item>
                    <a-descriptions-item label="办结时间">{{ item.endTime || '-' }}</a-descriptions-item>
                    <a-descriptions-item label="耗时">{{ item.duration || '-' }}</a-descriptions-item>
                  </a-descriptions>
                  <div v-if="item.commentList && item.commentList.length > 0">
                    <div v-for="(comment, index) in item.commentList" :key="index">
                      <a-divider>
                        <a-tag :color="approveTypeTag(comment.type)">{{ commentType(comment.type) }}</a-tag>
                        <a-tag color="gray">{{ comment.time }}</a-tag>
                      </a-divider>
                      <span>{{ comment.fullMessage }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="item.activityType === 'endEvent'">{{ item.createTime }} 结束流程</div>
              </a-card>
            </a-timeline-item>
          </a-timeline>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="track" tab="流程跟踪">
        <a-card class="box-card">
          <process-viewer
            :key="`designer-${loadIndex}`"
            :style="'height:' + height"
            :xml="processXml"
            :finishedInfo="finishedInfo"
            :allCommentList="historyProcNodeList"
          />
        </a-card>
      </a-tab-pane>
    </a-tabs>

    <a-modal v-model:open="returnDialog.visible" :title="returnDialog.title" @ok="submitReturn">
      <a-radio-group v-model:value="returnTaskKey">
        <a-radio-button v-for="item in returnTaskList" :key="item.id" :value="item.id">
          {{ item.name }}
        </a-radio-button>
      </a-radio-group>
    </a-modal>

    <a-modal v-model:open="userSelectDialog.visible" :title="userSelectDialog.title" width="60%" @ok="submitUserData">
      <a-row :gutter="20">
        <a-col :span="5">
          <a-card>
            <template #title>部门列表</template>
            <a-input v-model:value="deptName" placeholder="请输入部门名称" allowClear>
              <template #prefix><SearchOutlined /></template>
            </a-input>
            <a-tree
              :data="deptOptions"
              :fieldNames="{ title: 'label', key: 'id', children: 'children' }"
              @select="handleNodeClick"
              :filter="filterNode"
              ref="deptTreeRef"
            />
          </a-card>
        </a-col>
        <a-col :span="18">
          <a-table
            ref="userTable"
            :loading="userLoading"
            :dataSource="userList"
            :columns="userColumns"
            :rowSelection="
              userSelectType === 'copy' || userSelectType === 'next' || userSelectType === 'addSign' ? { onChange: handleSelectionChange } : null
            "
            @change="onTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'radio'">
                <a-radio :value="record.userId" v-model:checked="currentUserId" />
              </template>
            </template>
          </a-table>
          <a-pagination
            v-model:current="queryParams.pageNum"
            v-model:pageSize="queryParams.pageSize"
            :total="userTotal"
            @change="getList"
            show-size-changer
            show-total
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script setup name="Detail">
  import { processApi } from '/@/api/workflow/work';
  import { taskApi } from '/@/api/workflow/work';
  // import { identityApi } from '/@/api/workflow/identity';
  import { leaveApi } from '/@/api/business/leave';
  import { message, Modal } from 'ant-design-vue';
  import {
    PlusOutlined,
    SearchOutlined,
    CheckCircleOutlined,
    SwapOutlined,
    PlusCircleOutlined,
    SyncOutlined,
    UndoOutlined,
    CloseCircleOutlined,
  } from '@ant-design/icons-vue';
  // import LeaveDetail from '/@/views/business/leave/detail.vue';

  const route = useRoute();
  const router = useRouter();
  const { proxy } = getCurrentInstance();

  const loading = ref(true);
  const userList = ref([]);
  const processed = ref(false);
  const taskFormOpen = ref(false);
  const userMultipleSelection = ref([]);
  const userSelectType = ref();
  const currentUserId = ref();
  const userLoading = ref(false);
  const userTotal = ref(0);
  const loadIndex = ref(0);
  const height = ref(document.documentElement.clientHeight - 205 + 'px;');
  const processXml = ref('');
  const taskFormVisible = ref(false);
  const processFormList = ref([]);
  const taskFormData = ref([]);
  const historyProcNodeList = ref([]);
  const formVisible = ref(false);
  const finishedInfo = ref({});

  const deptName = ref('');
  const deptOptions = ref([]);

  const returnTaskList = ref();
  const returnTaskKey = ref();

  const copyUser = ref([]);
  const nextUser = ref([]);

  const taskFormRef = ref(null);
  const vFormRenderRef = ref(null);
  const deptTreeRef = ref(null);

  const returnDialog = reactive({
    visible: false,
    title: '退回流程',
  });

  const userSelectDialog = reactive({
    visible: false,
    title: '',
  });

  const taskForm = reactive({
    comment: '',
    procInsId: '',
    taskId: '',
    userId: '',
    copyUserIds: '',
    nextUserIds: '',
    vars: '',
    targetKey: '',
  });

  const rules = {
    comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
  };

  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  });

  const userColumns = [
    {
      title: '用户名称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      align: 'center',
    },
    {
      title: '手机',
      dataIndex: 'phonenumber',
      align: 'center',
    },
  ];

  const buttonPermissions = ref({
    complete: true,
    delegate: true,
    transfer: true,
    reject: true,
    return: true,
    addSign: true,
  });

  const activeTab = ref(computed(() => (processed.value ? 'approval' : 'form')));

  const initData = async () => {
    taskForm.procInsId = route.params.procInsId;
    taskForm.taskId = route.query.taskId;
    processed.value = route.query.processed === 'true';

    getProcessDetails(taskForm.procInsId, taskForm.taskId);
    loadIndex.value++;
  };

  const tagType = (val) => {
    if (val) {
      return 'success';
    } else {
      return 'info';
    }
  };

  const commentType = (val) => {
    switch (val) {
      case '1':
        return '通过';
      case '2':
        return '退回';
      case '3':
        return '驳回';
      case '4':
        return '委派';
      case '5':
        return '转办';
      case '6':
        return '终止';
      case '7':
        return '撤回';
    }
  };

  const approveTypeTag = (val) => {
    console.log(val);
    switch (val) {
      case '1':
        return 'success';
      case '2':
        return 'warning';
      case '3':
        return 'danger';
      case '4':
        return 'primary';
      case '5':
        return 'success';
      case '6':
        return 'danger';
      case '7':
        return 'info';
    }
  };

  const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
  };

  const handleNodeClick = (selectedKeys, info) => {
    getList(info.node.id);
  };

  const getTreeSelect = async () => {
    const res = await identityApi.deptTreeSelect();
    deptOptions.value = res.data;
  };

  const getList = async (deptId) => {
    userLoading.value = true;
    const res = await identityApi.selectUser({ deptId: deptId });
    userLoading.value = false;
    userList.value = res.rows;
    userTotal.value = res.total;
  };

  const formData = ref();
  const getProcessDetails = async (procInsId, taskId) => {
    const params = { procInsId: procInsId, taskId: taskId };
    const res = await processApi.detailProcess(params);
  

    const data = res.data;
    setComponentPath(data.formInfo.componentPath);
    console.log(data.buttonPermissions);
    formData.value = data.formData;

    if (data.buttonPermissions) {
      console.log(data.buttonPermissions.indexOf('complete'));
      if (data.buttonPermissions.indexOf('complete') === -1) {
        buttonPermissions.value.complete = false;
      }
      if (data.buttonPermissions.indexOf('delegate') === -1) {
        buttonPermissions.value.delegate = false;
      }
      if (data.buttonPermissions.indexOf('transfer') === -1) {
        buttonPermissions.value.transfer = false;
      }
      if (data.buttonPermissions.indexOf('reject') === -1) {
        buttonPermissions.value.reject = false;
      }
      if (data.buttonPermissions.indexOf('return') === -1) {
        buttonPermissions.value.return = false;
      }
      if (data.buttonPermissions.indexOf('addSign') === -1) {
        buttonPermissions.value.addSign = false;
      }
    }
    processXml.value = data.bpmnXml;
    processFormList.value = data.processFormList;
    taskFormVisible.value = data.existTaskForm;
    if (taskFormVisible.value) {
      taskFormData.value = data.taskFormData;
    }

    historyProcNodeList.value = data.historyProcNodeList;
    finishedInfo.value = data.flowViewer;
    formVisible.value = true;
    loading.value = false;
    nextTick(() => {
      processFormList.value.forEach((item, index) => {
        if (item.disabled) {
          vFormRenderRef.value[index].disableForm();
        }
      });
    });
  };

  const onSelectCopyUsers = () => {
    userMultipleSelection.value = copyUser;
    onSelectUsers('添加抄送人', 'copy');
  };

  const onSelectNextUsers = () => {
    userMultipleSelection.value = nextUser;
    onSelectUsers('指定审批人', 'next');
  };

  const onSelectUsers = (title, type) => {
    userSelectType.value = type;
    userSelectDialog.title = title;
    userSelectDialog.visible = true;
    getTreeSelect();
    getList();
  };

  const handleComplete = () => {
    taskFormRef.value.validate(async (valid) => {
      if (valid) {
        const res = await taskApi.complete(taskForm);
        message.success(res.msg);
        goBack();
      }
    });
  };

  const handleDelegate = () => {
    userSelectType.value = 'delegate';
    userSelectDialog.title = '委派任务';
    userSelectDialog.visible = true;
    getTreeSelect();
  };

  const handleAddSign = () => {
    userSelectType.value = 'addSign';
    userSelectDialog.title = '加签任务';
    userSelectDialog.visible = true;
    getTreeSelect();
  };

  const handleTransfer = () => {
    userSelectType.value = 'transfer';
    userSelectDialog.title = '转办任务';
    userSelectDialog.visible = true;
    getTreeSelect();
  };

  const handleReturn = async () => {
    taskFormRef.value.validate(async (valid) => {
      if (valid) {
        const res = await taskApi.returnList(taskForm);
        returnTaskList.value = res.data;

        returnDialog.visible = true;
      }
    });
  };

  const handleReject = async () => {
    Modal.confirm({
      title: '确认',
      content: '拒绝审批单流程会终止，是否继续?',
      async onOk() {
        await taskApi.rejectTask(taskForm);
        message.success('操作成功');
        goBack();
      },
    });
  };

  const goBack = () => {
    proxy.$tab.closePage(route);
    router.back();
  };

  const handleClose = (type, tag) => {
    let userObj = userMultipleSelection.value.find((item) => item.userId === tag.id);
    userMultipleSelection.value.splice(userMultipleSelection.value.indexOf(userObj), 1);
    if (type === 'copy') {
      copyUser.value = userMultipleSelection.value;
      if (copyUser.value && copyUser.value.length > 0) {
        const val = copyUser.value.map((item) => item.id);
        taskForm.copyUserIds = val instanceof Array ? val.join(',') : val;
      } else {
        taskForm.copyUserIds = '';
      }
    } else if (type === 'next') {
      nextUser.value = userMultipleSelection.value;
      if (nextUser.value && nextUser.value.length > 0) {
        const val = nextUser.value.map((item) => item.id);
        taskForm.nextUserIds = val instanceof Array ? val.join(',') : val;
      } else {
        taskForm.nextUserIds = '';
      }
    }
  };

  const changeCurrentUser = (val) => {
    currentUserId.value = val.userId;
  };

  const handleSelectionChange = (rows) => {
    console.log(rows);
    userMultipleSelection.value = rows;
  };

  const submitReturn = () => {
    taskFormRef.value.validate(async (valid) => {
      if (valid) {
        if (!returnTaskKey) {
          message.error('请选择退回节点！');
        }
        taskForm.targetKey = returnTaskKey.value;
        const res = await taskApi.returnTask(taskForm);
        message.success(res.msg);
        goBack();
      }
    });
    console.log('taskForm => ', taskForm.targetKey);
  };

  const submitUserData = () => {
    let type = userSelectType.value;
    if (type === 'copy' || type === 'next') {
      if (!userMultipleSelection || userMultipleSelection.value.length <= 0) {
        message.error('请选择用户');
        return false;
      }
      let userIds = userMultipleSelection.value.map((k) => k.userId);
      if (type === 'copy') {
        copyUser.value = userMultipleSelection.value;
        taskForm.copyUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
      } else if (type === 'next') {
        nextUser.value = userMultipleSelection.value;
        taskForm.nextUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
      }
      userSelectDialog.visible = false;
    } else {
      if (!taskForm.comment && type !== 'addSign') {
        message.error('请输入审批意见');
        return false;
      }
      if (!currentUserId.value) {
        message.error('请选择用户');
        return false;
      }
      taskForm.userId = currentUserId.value;
      if (type === 'delegate') {
        taskApi.delegate(taskForm).then((res) => {
          message.success(res.msg);
          goBack();
        });
      }
      if (type === 'transfer') {
        taskApi.transfer(taskForm).then((res) => {
          message.success(res.msg);
          goBack();
        });
      }
      if (type === 'addSign') {
        let userIds = userMultipleSelection.value.map((k) => k.userId);
        taskForm.userId = userIds instanceof Array ? userIds.join(',') : userIds;
        taskApi.addSign(taskForm).then((res) => {
          message.success(res.msg);
          goBack();
        });
      }
    }
  };

  const changeComponent = () => {
    setComponentPath('/business/leave/index.vue');
  };

  const componentPath = ref(defineAsyncComponent(() => import(`/@/views/business/emptyForm.vue`)));

  function setComponentPath(path) {
    componentPath.value = defineAsyncComponent(() => import(`/@/views${path}`));
  }
  const isMounted = ref(false);
  onMounted(async () => {
    await initData();
   
    isMounted.value = true;
  });

  onActivated(async () => {
    if (isMounted.value) {
      await initData();
      
    }
  });
</script>

<style scoped>
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }
  .clearfix:after {
    clear: both;
  }

  .box-card {
    width: 100%;
    margin-bottom: 20px;
  }

  .ant-tag {
    margin-right: 10px;
  }

  .ant-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
</style>
